package cn.piesat.scanning.business.common.algorithm.dataTransfer;

import cn.piesat.scanning.business.common.AlgorithmDefineAbstract;
import cn.piesat.scanning.dto.HtPathConfigurationDTO;
import cn.piesat.scanning.dto.HtScheduleJobDTO;
import cn.piesat.scanning.service.HtPathConfigurationService;
import cn.piesat.scanning.service.HtScheduleJobService;
import cn.piesat.scanning.utils.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * 数据迁移
 * @author xhl
 */
@Component
public class DataTransfer extends AlgorithmDefineAbstract {

    private static final Logger logger = LoggerFactory.getLogger(DataTransfer.class);

    @Autowired
    private HtPathConfigurationService htPathConfigurationService;
    @Autowired
    private HtScheduleJobService htScheduleJobService;

    @Override
    public void exec(Map<String, Object> params, String taskId) {
        //转移状态
        String status = (String) params.get("isCut");
        //文件名称正则
        String regex = (String) params.get("fileRegex");
        HtScheduleJobDTO taskDTO = htScheduleJobService.findById(taskId);
        HtPathConfigurationDTO pathDto = htPathConfigurationService.findById(taskDTO.getPathConfigId());
        //路径信息不为空，转移文件
        if(pathDto!=null){
            Collection<File> files = null;
            try{
                //根据正则匹配对应文件
                files = FileUtils.listFiles(new File(pathDto.getScanningPath()), new RegexFileFilter(regex), new RegexFileFilter(".*"));
                if(files.size()==0){
                    logger.info("[数据迁移] 目录{}下无匹配数据",pathDto.getScanningPath());
                }else{
                    logger.info("[数据迁移] 已找到{}个配置文件",files.size());
                }
                for (File file : files) {
                    File targetDir = new File(FilenameUtils.separatorsToUnix(pathDto.getOutputPath()+file.getParentFile().getAbsolutePath().replace(pathDto.getScanningPath(),"")));
                    try {
                        //判断是否拷贝
                        if (status.equals("false")) {
                            FileUtil.copyFileToDirectorySupportsSendfile(file, targetDir);
                        } else {
                            FileUtil.moveFileToDirectorySupportsSendfile(file, targetDir);
                        }
                    } catch (IOException e) {
                        logger.error("文件转移任务异常!taskId:{},fileName:{}",taskDTO.getId(),file.getName());
                    }
                }
            }catch (Exception e){
                logger.error("扫描文件异常:{}",e.getMessage());
            }
        }
    }

}
